// src/views/commission/index.vue
<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-input
          v-model="listQuery.search"
          placeholder="请输入用户ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleFilter"
        />
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="primary" @click="handleCreate">新增</el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        stripe
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column type="index" width="50" label="序号" align="center" />
        <el-table-column prop="order_id" label="订单ID" width="100" />
        <el-table-column prop="from_user_id" label="来源用户" width="100" />
        <el-table-column prop="to_user_id" label="获得用户" width="100" />
        <el-table-column prop="amount" label="金额" width="100" />
        <el-table-column prop="rate" label="比例(%)" width="100" />
        <el-table-column prop="created_at" label="时间" width="180" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="listQuery.page"
          :page-size="listQuery.per_page"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogStatus === 'create' ? '新增记录' : '编辑记录'"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="订单ID" prop="order_id">
          <el-input-number
            v-model="form.order_id"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="来源用户ID" prop="from_user_id">
          <el-input-number
            v-model="form.from_user_id"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="获得用户ID" prop="to_user_id">
          <el-input-number
            v-model="form.to_user_id"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="form.amount"
            :min="0"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="比例(%)" prop="rate">
          <el-input-number
            v-model="form.rate"
            :min="0"
            :step="0.01"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  fetchCommissionList,
  addCommission,
  updateCommission,
  deleteCommission,
} from "@/api/commission";

const list = ref([]);
const total = ref(0);
const listLoading = ref(false);
const dialogVisible = ref(false);
const dialogStatus = ref("create");
const formRef = ref(null);

const listQuery = reactive({
  page: 1,
  per_page: 20,
  search: "",
});

const form = reactive({
  order_id: "",
  from_user_id: "",
  to_user_id: "",
  amount: 0,
  rate: 0,
});

const rules = {
  order_id: [{ required: true, message: "请输入订单ID", trigger: "blur" }],
  from_user_id: [
    { required: true, message: "请输入来源用户ID", trigger: "blur" },
  ],
  to_user_id: [
    { required: true, message: "请输入获得用户ID", trigger: "blur" },
  ],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
  rate: [{ required: true, message: "请输入比例", trigger: "blur" }],
};

const getList = async () => {
  listLoading.value = true;
  try {
    const res = await fetchCommissionList(listQuery);
    list.value = res.data.items;
    total.value = res.data.total;
  } catch (err) {
    ElMessage.error("获取失败");
  } finally {
    listLoading.value = false;
  }
};

const handleFilter = () => {
  listQuery.page = 1;
  getList();
};

const handleSizeChange = (val) => {
  listQuery.per_page = val;
  getList();
};

const handleCurrentChange = (val) => {
  listQuery.page = val;
  getList();
};

const resetForm = () => {
  if (formRef.value) formRef.value.resetFields();
  Object.assign(form, {
    order_id: "",
    from_user_id: "",
    to_user_id: "",
    amount: 0,
    rate: 0,
  });
};

const handleCreate = () => {
  resetForm();
  dialogStatus.value = "create";
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  Object.assign(form, row);
  dialogStatus.value = "edit";
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  try {
    if (dialogStatus.value === "create") {
      await addCommission(form);
      ElMessage.success("添加成功");
    } else {
      await updateCommission(form.id, form);
      ElMessage.success("修改成功");
    }
    dialogVisible.value = false;
    getList();
  } catch (err) {
    ElMessage.error("操作失败");
  }
};

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除记录 ${row.id} 吗？`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteCommission(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (err) {
      ElMessage.error("删除失败");
    }
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  margin-bottom: 10px;
}
.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style>
